package com.emm.yixun.website.controller.estate;
//框架包
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.ProjectHouseType;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.ProjectHouseTypeDto;
import com.emm.yixun.common.model.dto.ProjectRoomDto;
import com.emm.yixun.common.model.dto.ProjectRoomPriceDto;
import com.emm.yixun.common.model.dto.RootClass;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.LevelEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.estate.service.ProjectHouseTypeServiceFacade;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.marketing.service.PriceSchemeServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.system.service.MerchantServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
//common
//website
//变化的引用
@Controller
@RequestMapping("/estate/projectRoom/")
public class ProjectRoomController extends BaseController<ProjectRoom> {

	@Autowired
	private ProjectRoomServiceFacade projectRoomServiceFacade;
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	@Autowired
	private ProjectHouseTypeServiceFacade projectHouseTypeServiceFacade;
	
	@Autowired
	private PriceSchemeServiceFacade priceSchemeServiceFacade;
	@Autowired
	private MerchantServiceFacade merchantServiceFacade;
	
	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade;

	@RequestMapping(value = "index")
	public String index(ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
			// 查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			return "/estate/projectRoom/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	// 查看
	@RequestMapping(value = "detail")
	public String detail(Long id, ModelMap map) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectRoom:view"))) {
			try {
				map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
				Response<ProjectRoom> response = projectRoomServiceFacade.findById(id);
				if (response.isSuccess()) {
					Map<String, String> projectMap = new HashMap<String, String>();
					ProjectRoom room = response.getEntity();
					if (room.getUnitId() != null && StringUtils.isNotEmpty(String.valueOf(room.getUnitId()))) {
						projectMap = projectServiceFacade.projectLevelName(room.getUnitId(), "4");
					} else if (room.getBuildingId() != null
							&& StringUtils.isNotEmpty(String.valueOf(room.getBuildingId()))) {
						projectMap = projectServiceFacade.projectLevelName(room.getBuildingId(), "3");
					} else if (room.getPremisesId() != null
							&& StringUtils.isNotEmpty(String.valueOf(room.getPremisesId()))) {
						projectMap = projectServiceFacade.projectLevelName(room.getPremisesId(), "2");
					} else {
						projectMap = projectServiceFacade.projectLevelName(room.getProjectId(), "1");
					}

					map.addAttribute("manageObject", projectMap.get("manageObject") + "->"
							+ response.getEntity().getRoomName());
					map.addAttribute("parentName", projectMap.get("manageObject"));
					if(!StringUtils.isEmpty(response.getEntity().getIndustMark())){
					    Response<BaseCodeValue> baseCode =  baseCodeValueServiceFacade.findById(new Long(response.getEntity().getIndustMark()));
					    map.addAttribute("baseCode", baseCode.getEntity());
					}
					// 房产类型
					Map<Long, String> phtMap = new HashMap<Long, String>();
					ProjectHouseTypeDto phtDto = new ProjectHouseTypeDto();
					phtDto.setProjectId(response.getEntity().getProjectId());
					ResponseList<ProjectHouseType> phtResponse = projectHouseTypeServiceFacade.findByDto(phtDto);
					if (phtResponse.isSuccess() && null!=phtResponse.getEntity()) {
						List<ProjectHouseType> phtList = phtResponse.getEntity();
						for (ProjectHouseType pht : phtList) {
							phtMap.put(pht.getId(), pht.getHouseTypeName());
						}
					}
					User user = ShiroUtil.getCurrentUser();
					//认筹开关,默认未关闭
					boolean payDepositOff = false;
					Response<Boolean> responseB = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
					if(response.isSuccess()){
						payDepositOff = responseB.getEntity();
					}
					map.put("payDepositOff", payDepositOff);
					map.addAttribute("phtMap", phtMap);
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
				map.addAttribute("ar", ar);
				return "/estate/projectRoom/detail";
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return Const.NO_AUTHORIZED_URL;
	}

	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes add(ProjectRoomDto dto) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectRoom:add"))) {
			try {
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				dto.setCreateUserId(user.getId());
				dto.setDelFlag("0");
				dto.setUpdateUserId(user.getId());
				dto.setUpdateTime(new Date());
				Response<ProjectRoomDto> response = projectRoomServiceFacade.save(dto);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 查看
	@RequestMapping(value = "view", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes view(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectRoom:view"))) {
			try {
				Response<ProjectRoom> response = projectRoomServiceFacade.findById(id);
				if (response.isSuccess()) {
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(ProjectRoomDto dto, HttpServletRequest request) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用修改接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectRoom:edit"))) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String salesPermissionDateOrigin = request.getParameter("salesPermissionDateOrigin");
				if (StringUtils.isNotEmpty(salesPermissionDateOrigin)) {
					dto.setSalesPermissionDate(sdf.parse(salesPermissionDateOrigin));
				}
				Response<Integer> response = projectRoomServiceFacade.updateByPrimaryKey(dto, true);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				} else {
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectRoom:delete"))) {
			try {
				Response<Integer> response = projectRoomServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}

	// 分页查询
	@RequestMapping(value = "componentList", method = RequestMethod.POST)
	@ResponseBody
	public Page<ProjectRoomPriceDto> componentList(ProjectRoomDto dto, String treeId, Integer page, Integer limit) {
		try {
			String id = treeId.split("_")[1];
			Long realId = Long.valueOf(id);
			if (treeId.indexOf("PROJECT") != -1) {
				dto.setProjectId(realId);
			} else if (treeId.indexOf("PREMISES") != -1) {
				dto.setPremisesId(realId);
			} else if (treeId.indexOf("BUILDING") != -1) {
				dto.setBuildingId(realId);
			} else if (treeId.indexOf("UNIT") != -1) {
				dto.setUnitId(realId);
			} else if (treeId.indexOf("ROOM") != -1) {
				dto.setId(realId);
			}

			User user = ShiroUtil.getCurrentUser();
			dto.setPermissionUserId(user.getId());
			
			//项目数据权限资源缓存
			String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
			if(null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())){
				dto.setResourcesCode(resourcesCode);
			}else if("".equals(resourcesCode)){
				ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
			}
			
			Page<ProjectRoomPriceDto> response = projectRoomServiceFacade.findRoomPricePageByDto(dto, PageUtil.begin(page, limit), limit);
			if (response.getSuccess()) {
				if (null == response.getRows())
					response.setRows(new ArrayList<ProjectRoomPriceDto>());
				response.setPageNumber(page);
				return response;
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new Page<ProjectRoomPriceDto>();
	}

	@RequestMapping(value = "toBatchUpdate")
	public String toBatchUpdate(ModelMap map, Long projectId, Long premisesId, Long buildingId, Long unitId) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectRoom:saveBatchData")) {
			// 查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			map.put("projectId", projectId);
			map.put("premisesId", premisesId);
			map.put("buildingId", buildingId);
			map.put("unitId", unitId);
			return "/estate/projectRoom/batchUpdate";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	@RequestMapping(value = "findBatchData")
	@ResponseBody
	public Page<ProjectRoom> findBatchData(ProjectRoomDto dto, Integer page, Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectRoom:saveBatchData")) {
			try {
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				Page<ProjectRoom> response = projectRoomServiceFacade.findPageByDto(dto, PageUtil.begin(page, limit),
						limit);
				if (response.getSuccess()) {
					if (null == response.getRows())
						response.setRows(new ArrayList<ProjectRoom>());
					response.setPageNumber(limit);
					return response;
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);

			}
		}
		return new Page<ProjectRoom>();
	}

	@RequestMapping(value = "saveBatchData")
	@ResponseBody
	public String saveBatchData(String jsonArray) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		jsonArray = "[" + jsonArray + "]";
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectRoom:saveBatchData")) {
			try {
				Response<Boolean> response = projectRoomServiceFacade.saveBatchData(jsonArray);
				if (response.isSuccess() && response.getEntity()) {
					return "0";
				}
				return "1";
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
			return "1";
		}
		// 没权限
		return "-1";
	}

	// 分页查询
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public Page<ProjectRoomDto> list(ProjectRoomDto dto, Integer limit, Integer page) {

		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:room:list")) {
			try {
				dto.setOrders(" t.create_time desc ");
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				dto.setPermissionUserId(user.getId());
				
				//项目数据权限资源缓存
				String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
				if(null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())){
					dto.setResourcesCode(resourcesCode);
				}else if("".equals(resourcesCode)){
					ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
				}
				if(StringUtils.isNotEmpty(dto.getIds())){
					dto.setIds("("+dto.getIds()+")");
				}
				//可售
				if(StringUtils.isEmpty(dto.getRoomStatus())){
					dto.setRoomStatus("1");
				}
				Response<Page<ProjectRoomDto>> response = projectRoomServiceFacade.getProjectRoomDtoPage(dto, limit,page);
				if (response.isSuccess()) {
					Page<ProjectRoomDto> pages = response.getEntity();
					List<ProjectRoomDto> list = pages.getRows();
					if(null != list){
						for (ProjectRoomDto projectRoomDto : list) {
							if (projectRoomDto != null && projectRoomDto.getEffectiveDate() != null) {
								Long day = DateUtils.getDaysSub(projectRoomDto.getEffectiveDate(), new Date());
								projectRoomDto.setDay(day);
							}
						}
					}
					pages.setPageNumber(page);
					return pages;
				} else {
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return new Page<ProjectRoomDto>();
	}
	
	@RequestMapping(value = "modelList", method = RequestMethod.POST)
	@ResponseBody
	public Page<ProjectRoomDto> modelList(ProjectRoomDto dto, Integer limit, Integer page) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:room:list")) {
			try {
				dto.setOrders(" t.create_time desc ");
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				dto.setPermissionUserId(user.getId());
				
				//项目数据权限资源缓存
				String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
				if(null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())){
					dto.setResourcesCode(resourcesCode);
				}else if("".equals(resourcesCode)){
					ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
				}
				dto=query(dto);
				Response<Page<ProjectRoomDto>> response = projectRoomServiceFacade.getProjectRoomDtoPage(dto, limit,page);
				return response.getEntity();
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return new Page<ProjectRoomDto>();
	}
	
	public ProjectRoomDto query(ProjectRoomDto dto){
		if(!StringUtils.isEmpty(dto.getRoomQuery())){
			String str = dto.getRoomQuery();
			String sub = str.substring(0, str.indexOf("_"));
			Long busId = new Long(str.substring(str.indexOf("_")+1, str.length()));
			LevelEnum lavelEnum = LevelEnum.getByNo(sub);
			if(lavelEnum!=null){
				if(lavelEnum.getCode().equals(LevelEnum.LevelEnum_1.getCode())){
					dto.setProjectId(busId);
				}else if(lavelEnum.getCode().equals(LevelEnum.LevelEnum_2.getCode())){
					dto.setPremisesId(busId);
				}else if(lavelEnum.getCode().equals(LevelEnum.LevelEnum_3.getCode())){
					dto.setBuildingId(busId);
				}else if(lavelEnum.getCode().equals(LevelEnum.LevelEnum_4.getCode())){
					dto.setUnitId(busId);
				}else if(lavelEnum.getCode().equals(LevelEnum.LevelEnum_5.getCode())){
					dto.setId(busId);
				}
			}
		}
		if(!StringUtils.isEmpty(dto.getModelRoomStatus())){
			ArrayList<String> array = new ArrayList<String>();
			String[] ids = dto.getModelRoomStatus().split(",");
			for (int i = 0; i < ids.length; i++) {
				array.add(ids[i]);
			}
			dto.setRoomStatusList(array);
		}
		return dto;
	}
	
	@RequestMapping(value = "findProjectHouseType")
	public @ResponseBody List<ProjectHouseType> findProjectHouseType(ProjectRoomDto dto){
		dto=query(dto);
		ResponseList<ProjectRoom> list = projectRoomServiceFacade.findByDto(dto);
		if(list.isSuccess()&&list.getEntity()!=null&&list.getEntity().size()>0){
			Long projectId = list.getEntity().get(0).getProjectId();
			ProjectHouseTypeDto entity = new ProjectHouseTypeDto();
			entity.setProjectId(projectId);
			entity.setDelFlag(DelFlagEnum.UNDEL.getNo());
			return projectHouseTypeServiceFacade.findByDto(entity).getEntity();
		}
		return null;
	}
	
	@RequestMapping(value = "roomDetail", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes roomDetail(Long id) {
		AjaxRes ar = getAjaxRes();
		try {
			Response<ProjectRoomPriceDto> response = projectRoomServiceFacade.findRoomPriceDetail(id);
			if (response.isSuccess()) {
				ar.setSucceed(response.getEntity());
			} else {
				ar.setFailMsg(Const.DATA_FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}
	@RequestMapping("findPriceByRoomId")
	public @ResponseBody AjaxRes findPriceByRoomId(Long roomId,Long payDepositId, Long subscribeId){
		AjaxRes ar = getAjaxRes();
		try {
			Response<BigDecimal> response = priceSchemeServiceFacade.findPriceByRoomId(roomId,payDepositId,subscribeId);
			if (response.isSuccess()) {
				ar.setSucceed(response.getEntity());
			} else {
				ar.setFailMsg(Const.DATA_FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}
	@RequestMapping(value = "findPayDeposit")
	public @ResponseBody AjaxRes findPayDeposit(Long roomId,Long paydepositId){
		AjaxRes ar = getAjaxRes();
		Response<ProjectRoomPriceDto> response = projectRoomServiceFacade.findPayDeposit(roomId, paydepositId);
		if(response.isSuccess()){
			ar.setSucceed(response.getEntity());
		}
		return ar;
	}
	
	@RequestMapping(value = "findSubscribe")
	public @ResponseBody AjaxRes findSubscribe(Long roomId,Long subscribeId){
		AjaxRes ar = getAjaxRes();
		Response<ProjectRoomPriceDto> response = projectRoomServiceFacade.findSubscribe(roomId, subscribeId);
		Response<ProjectRoomPriceDto> resRoom = projectRoomServiceFacade.findRoomPriceDetail(roomId);
		BigDecimal roomDiscountRate = new BigDecimal(0);
		if(response.isSuccess()){
			if(resRoom.isSuccess()){
				roomDiscountRate = resRoom.getEntity().getDiscountRate();
				response.getEntity().setDiscountRate(roomDiscountRate);
			}
			ar.setSucceed(response.getEntity());
		}
		return ar;
	}
	
	@RequestMapping(value = "findRoomList")
	public @ResponseBody
	RootClass findRoomList(ProjectRoomDto dto) {
		User user = ShiroUtil.getCurrentUser();
		dto.setDelFlag("0");
		dto.setMerchantId(user.getMerchantId());
		ResponseList<ProjectRoom> roomList = projectRoomServiceFacade.findByDto(dto);
		RootClass root = new RootClass();
		root.setRoot(roomList.getEntity());
		return root;
	}
	
}
